# -*- coding:utf-8 -*-
# @Time: 2020/9/7 14:23
# @Author: gupeng
# @File: string_test.py

from redis import Redis
from str.cache import Cache
from str.lock import Lock
from str.article import Article
from str.log import Log
from str.id_generator import IdGenerator
from str.counter import Counter
from str.limiter import Limiter

client = Redis()


def cache_test():
    cache = Cache(client)
    cache.set('name', 'gupeng')
    print('name = ' + str(cache.get('name')))
    print('old name = ' + str(cache.update('name', 'Gu Peng')))
    print('new name = ' + str(cache.get('name')))


def lock_test():
    lock = Lock(client, 'lock_key')
    print('first lock result is ' + str(lock.acquire()))
    print('second lock result is ' + str(lock.acquire()))
    print('lock release result is ' + str(lock.release()))
    print('second lock result is ' + str(lock.acquire()))
    print('lock release result is ' + str(lock.release()))


def article_test():
    article = Article(client, 1)
    print('创建article结果：' + str(article.create('python', 'This is python', 'gupeng')))
    print('获取article结果：' + str(article.get()))
    print('修改article结果：' + str(article.update(content='This is redis')))
    print('获取修改后的article结果：' + str(article.get()))
    print('length of article is ' + str(article.get_content_len()))
    print('preview of article is ' + str(article.get_content_preview(10)))


def id_generator_test():
    id_generator = IdGenerator(client, 'id_generator')
    print('create a id_generator start from 10 result is ' + str(id_generator.reserve(10)))
    print('id_generator++ result is ' + str(id_generator.product()))


def log_test():
    log = Log(client, 'log_key')
    log.add('row1 log')
    log.add('row2 log')
    log.add('row3 log')
    log.add('row4 log')
    logs = log.get_all()
    for c in logs:
        print(c)


def counter_test():
    counter = Counter(client, 'counter')
    print('increase counter = ' + str(counter.increase()))
    print('increase counter = ' + str(counter.increase()))
    print('decrease counter = ' + str(counter.decrease()))
    print('decrease counter = ' + str(counter.decrease()))
    print('reset counter old value = ' + str(counter.reset()))


def limiter_test():
    limiter = Limiter(client, 'limiter')
    limiter.set_max_execute_times(2)
    print('remain result is ' + str(limiter.remaining_execute_times()))
    print('action result is ' + str(limiter.still_valid_to_execute()))
    print('remain result is ' + str(limiter.remaining_execute_times()))
    print('action result is ' + str(limiter.still_valid_to_execute()))
    print('remain result is ' + str(limiter.remaining_execute_times()))
    print('action result is ' + str(limiter.still_valid_to_execute()))
    print('remain result is ' + str(limiter.remaining_execute_times()))


if __name__ == '__main__':
    # cache_test()
    # lock_test()
    # article_test()
    # log_test()
    # id_generator_test()
    # counter_test()
    limiter_test()
